// 1.导入express
const express = require('express');
const cors = require('cors')
const JWT = require('./utils/jwt')
const RSA = require('./utils/rsa')
const rsa = new RSA()
// const plainText = "Hello, RSA encryption!";
// // 公钥加密 & 私钥解密
// const encryptedWithPublicKey = rsa.publicEncrypt(plainText);
// console.log("加密后（公钥加密）：", encryptedWithPublicKey);

// const decryptedWithPrivateKey = rsa.privateDecrypt(encryptedWithPublicKey);
// console.log("解密后（私钥解密）：", decryptedWithPrivateKey);

//2.创建web服务器
const app = express();
app.use(express.static('dist'))
app.use(express.static('files'))
app.use(cors())
// 解析 url-encoded格式的表单数据
app.use(express.urlencoded({ extended: false }));
// 解析json格式的表单数据
app.use(express.json());
//导入路由模块
const router= require('./api/apiRouter')
// 登录验证拦截
// 白名单whiteList
const whiteList = ['/api/getVersionUpdate','/api/searchVideoList','/api/getPosition','/api/savePosition','/api/login','/api/addUser','/api/sendVerificationCode','/api/resetPassword','/favicon.ico']
app.use('*',(req,res,next)=>{
    console.log(`请求的路径：${req.baseUrl}`);
    
    if (whiteList.includes(req.baseUrl) || req.baseUrl.indexOf('/uploads')!=-1) return next()
    let token = req.get('Authorization')
    if (token) {
        const result = JWT.verifyToken(token.split(' ')[1])
        console.log(result);
        
        if (result) {
            next()
        } else {
            res.status(401).send({ code: 401, msg: '登录信息已失效，请重新登录' })
        }
    } else { 
        res.status(401).send({ code: 401, msg: '未携带token' })
    }
})
//把路由模块注册到app上
app.use('/api',router)

//3.调用app.listen(端口号，启动成功的回调函数），启动服务器
app.listen(3000,()=>{
    console.log('express server running at http://127.0.0.1:3000')
})
